package cn.wolfcode.cloud.shop.service.impl;

import cn.wolfcode.cloud.redis.RedisService;
import cn.wolfcode.cloud.shop.common.BusinessException;
import cn.wolfcode.cloud.shop.domain.User;
import cn.wolfcode.cloud.shop.mapper.UserMapper;
import cn.wolfcode.cloud.shop.redis.MemberKeyPrefix;
import cn.wolfcode.cloud.shop.service.IUserServer;
import cn.wolfcode.cloud.shop.util.MD5Util;
import cn.wolfcode.cloud.shop.util.MemberCodeMsg;
import cn.wolfcode.cloud.shop.web.result.LoginVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.UUID;

/**
 * @Description: 用户业务逻辑实现类
 * @Author: 伍家钰
 * @Date: 2020/9/5 19:20
 * @Version: 1.0
 */
@Service
public class UserServerImpl implements IUserServer {
    @Autowired
    private UserMapper userMapper;

    @Autowired
    private RedisService redisService;

    @Override
    public User selectById(Long id) {
        return userMapper.selectById(id);
    }

    @Override
    public String login(LoginVo vo) {
        // 1.判断账号密码是否为空
        if (!StringUtils.hasText(vo.getUsername()) || !StringUtils.hasText(vo.getPassword())) {
            // 抛出账号密码不能为空
            throw new BusinessException(MemberCodeMsg.LOGIN_ERROR);
        }
        // 2.根据id(手机号)查询用户是否存在
        Long id = Long.valueOf(vo.getUsername());
        User user = userMapper.selectById(id);
        if (user == null) {
            // 抛出账号不存在
            throw new BusinessException(MemberCodeMsg.USERNAME_NO_EXIST);
        }
        // 3.判断密码是否正确
        // 拿到用户中密码的盐
        String salt = user.getSalt();
        String p = user.getPassword();
        String password = MD5Util.encodCry(salt, vo.getPassword());
        // 校验用户密码
        if (!password.equals(p)) {
            throw new BusinessException(MemberCodeMsg.PASSWORD_ERROR);
        }
        String token = createToken(user);
        return token;
    }

    public String createToken(User user) {
        String token = UUID.randomUUID().toString().replace("-", "");
        // 将token存入redis中
        redisService.set(MemberKeyPrefix.USER_TOKEN, token, user);
        return token;
    }
}
